<template>
  <div class="app-container">
    <el-row>
      <!-- 树结构 -->
      <el-col :span="6" :xs="24">
        <div class="mainbox-left">
          <div class="box-card">
            <ProcessClassifiy
              name="流程分类"
              :handle="true"
              :default-type="defaultType"
              @treeClick="treeClick"
            />
          </div>
        </div>
      </el-col>
      <el-col :span="18" :xs="24" style="padding-left: 0px">
        <div class="none2-border3 userlist mainbox">
          <dt-table
            v-loading="loading"
            :table-opts="tableOpts"
            :pagination-data="{
              total: total,
              queryParams: queryParams,
            }"

            @pagination="pagination"
            @handleSelectionChange="handleSelectionChange"
            @searchReset="handleReset"
            @searchChange="handleQuery"
          >
            <template #versionSlot="versionSlot">
              <span v-if="versionSlot.param.version">V{{ versionSlot.param.version }}</span>
              <span v-else>-</span>
            </template>
            <template #operatorBtn="scope">
              <el-button size="mini" v-permission="['PROCESSDESIGN_PROCESSDESIGN_STATUS_BUTTON']" :disabled="categoryKey == 'lowcode' || scope.param.categoryKey =='lowcode' "
                         @click="statusChange(scope.param)">{{ scope.param.statusFlag===1?'禁用':'启用' }}</el-button>
            </template>
          </dt-table>
        </div>
      </el-col>
    </el-row>
    <!-- 新建流程 -->
    <!-- <newProcess ref="newProcess" /> -->
    <!-- 选择分类 -->
    <dt-dialog
      title="选择分类"
      :visible.sync="openClassify"
      comfirm-label="确定"
      @comfirmBtn="classifySubmit"
      @closeDialog="classifyCancel"
    >
      <div slot="content">
        <div class="title">分类名称</div>
        <div class="classifyContent">
          <el-radio-group v-model="selectClassify">
            <el-radio v-for="item in allClassifyList" :key="item.categoryId" class="radio"
                      :label="item.categoryId">{{ item.categoryName }}</el-radio>
          </el-radio-group>
        </div>
      </div>
    </dt-dialog>
    <!-- 复制弹窗 -->
    <dt-dialog
      :title="title"
      :visible.sync="open"
      @comfirmBtn="submitForm"
      @closeDialog="cancel"
    >
      <div slot="content">
        <el-form
          ref="copyForm"
          :model="form"
          :rules="copyRules"
          label-width="82px"
        >
          <el-form-item label="流程名称" prop="processName">
            <el-input v-model.trim="form.processName" placeholder="请输入流程名称" maxlength="20"
                      show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="流程编码" prop="processKey">
            <el-input v-model.trim="form.processKey" placeholder="请输入流程编码" maxlength="30"
                      show-word-limit class="limit" @input="inputValue($event, 'processKey')" />
          </el-form-item>
        </el-form>
      </div>
    </dt-dialog>
  </div>
</template>

<script>
import sysUserApi from '@/framework/api/userCenter/sysUser'
import ProcessClassifiy from './components/processClassifiy.vue'
import { listprocessDesign, deploy, copy, delprocessDesign, enable } from '@/framework/api/processDesign/processDesign'
import classifiy from '@/framework/api/processDesign/processClassifiy.js'

export default {
  name: 'ProcessDesign',
  dicts: ['user_status'],
  components: {
    ProcessClassifiy
  },
  beforeRouteLeave(to, from, next) {
    localStorage.removeItem('processQuery')
    next()
  },
  data() {
    return {
      defaultType: '',
      selectClassify: '',
      allClassifyList: [],
      copyRules: {
        processName: [
          { required: true, message: '请输入流程名称', trigger: 'blur' }
        ],
        processKey: [
          { required: true, message: '请输入流程编码', trigger: 'blur' }
        ]
      },
      openClassify: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        processKey: null,
        processName: null
      },
      open: false,
      filterText: '',
      tree: [],
      title: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentKey: '',
      form: {
        processName: '',
        processType: ''
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 搜索---下拉框数据
      optionsList: [
        {
          label: '我创建的',
          id: 1
        },
        {
          label: '我维护的',
          id: 2
        }
      ],
      tableOpts: {
        firstTableCol: {
          select: false
        },
        tableData: [],
        rowKey: 'processKey',
        toolbarBtn: [
          {
            label: '新建流程',
            type: 'primary',
            permission: ['PROCESSDESIGN_PROCESSDESIGN_ADD_BUTTON'],
            click: (type) => {
              this.handleAdd()
            },
            disabled: () => {
              return this.categoryKey == 'lowcode'
            }
          }
        ],
        // 表头 表格标题
        tableCol: [
          {
            prop: 'processName',
            label: '流程名称',
            show: true,
            search: true,
            width: 150,
            fixed: true
          },
          {
            prop: 'processKey',
            label: '流程编号',
            show: true,
            search: true,
            width: 150
          },
          // {
          //   prop: 'description',
          //   label: '描述',
          //   show: true
          // },
          {
            prop: 'categoryName',
            label: '分类',
            show: true,
            width: 130
          },
          {
            prop: 'version',
            label: '版本',
            show: true,
            slotName: 'versionSlot'
          },
          {
            prop: 'status',
            label: '状态',
            show: true,
            formatter: (row) => {
              const obj = { 0: '草稿', 1: '已发布', 2: '取消发布' }
              return obj[row.status]
            }
          },
          {
            prop: 'updateTime',
            label: '最近修改时间',
            show: true,
            width: 150
          },
          {
            prop: 'updateUserName',
            label: '最近修改人',
            show: true,
            width: 150
          },
          {
            prop: 'createTime',
            label: '创建时间',
            show: true,
            width: 150
          },
          {
            prop: 'createuserName',
            label: '创建人',
            show: true
          },
          {
            prop: 'processBelong',
            label: '流程所属',
            show: false,
            search: true,
            searchType: 'select',
            searchData: () => {
              return [
                { label: '我创建的', value: '1' },
                { label: '我维护的', value: '2' }
              ]
            }
          }
        ],
        // 操作表格每一条
        operator: {
          fixed: 'right',
          width: 292,
          operatorBtn: [
            {
              text: '修改',
              size: 'mini',
              permission: ['PROCESSDESIGN_PROCESSDESIGN_UPDATE_BUTTON'],
              click: (row, col, cellValue) => {
                return this.handleUpdate(row)
              },
              disabledChange: (row) => {
                return this.categoryKey == 'lowcode' || row.categoryKey == 'lowcode'
              }
            },
            {
              text: '复制',
              size: 'mini',
              permission: ['PROCESSDESIGN_PROCESSDESIGN_COPY_BUTTON'],
              click: (row, col, cellValue) => {
                return this.copyRoute(row)
              },
              disabledChange: (row) => {
                return this.categoryKey == 'lowcode' || row.categoryKey == 'lowcode'
              }
            },
            {
              text: '删除',
              size: 'mini',
              type: 'danger',
              permission: ['PROCESSDESIGN_PROCESSDESIGN_DELETE_BUTTON'],
              click: (row, col, cellValue) => {
                return this.handleDelete(row)
              },
              disabledChange: (row) => {
                return this.deleteDisabled(row)
              }
            }
            // {
            //   text: '禁用',
            //   size: 'small',
            //   click: (row, col, cellValue) => {
            //     return this.statusChange(row)
            //   }
            // }
          ]
        }
      },
      orgName: '',
      uploadLoading: false,
      handleImportTemplate: sysUserApi.downloadTemplate,
      multipleSelection: [],
      categoryKey: ''
    }
  },
  computed: {
    lightTheme() {
      return `${this.$store.state.settings.theme}19`
    }
  },
  created() {
    if (localStorage.getItem('processQuery')) {
      this.defaultType = localStorage.getItem('processQuery')
    }
  },
  methods: {
    inputValue(value, type) {
      if (/[^\da-zA-Z_]/g.test(value)) {
        this.form[type] = value.replace(/[^\da-zA-Z_]/g, '')
      }
    },
    goJump(param) {
      localStorage.setItem('processQuery', this.queryParams.categoryId)
      window.location.href = `${process.env.VUE_APP_PROCESS_SRC}/#/?${param}`
      this.selectClassify = ''
    },
    classifySubmit() {
      if (!this.selectClassify) {
        this.$dtModal.msgWarning('请选择流程分类')
        return
      }
      this.goJump(`categoryId=${this.selectClassify}`)
    },
    classifyCancel() {
      this.selectClassify = ''
    },
    // 获取页面列表
    getList() {
      this.loading = true
      const { categoryId } = this.queryParams
      listprocessDesign({ ...this.queryParams, categoryId: categoryId === 'undefined' ? '' : categoryId }).then(({ data: response }) => {
        this.tableOpts.tableData = response.rows
        this.total = response.totalRows
        this.loading = false
      })
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('copyForm')
    },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      this.queryParams = { ...this.queryParams, ...formModel }
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams = {
        processName: '',
        processKey: '',
        processBelong: '',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.queryParams.categoryId) {
        this.goJump(`categoryId=${this.queryParams.categoryId}`)
        return
      }
      classifiy.getGroupTree().then((res) => {
        this.allClassifyList = res.data.filter((item) => {
          return item.categoryKey != 'lowcode'
        })
      })
      this.openClassify = true
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.goJump(`procdefId=${row.procdefId}`)
    },
    statusChange(row) {
      enable({ procdefId: row.procdefId, statusFlag: row.statusFlag === 1 ? 2 : 1 }).then(({ data }) => {
        this.getList()
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 复制路径
    submitForm() {
      this.$refs.copyForm.validate((valid) => {
        if (valid) {
          this.loading = true
          copy(this.form).then(() => {
            this.getList()
            this.$dtModal.msgSuccess('复制成功')
            this.open = false
            this.loading = false
            this.getList()
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },

    // 部署按钮
    handleDeploy(row) {
      this.loading = true
      deploy(row.id).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('部署成功')
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 打开复制弹窗
    copyRoute(row) {
      this.open = true
      this.title = '复制模型'
      this.form = {
        procdefId: row.procdefId,
        processName: row.processName,
        processKey: row.processKey
      }
    },

    // 分页
    pagination() {
      this.getList()
    },
    // 点击左侧树节点
    treeClick(categoryId, categoryKey) {
      this.queryParams.categoryId = categoryId
      this.categoryKey = categoryKey
      this.getList()
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$dtModal.confirm(`您删除"${row.processName}"后对应的流程实例也会被删除，请谨慎操作？`).then(() => {
        return delprocessDesign(row.procdefId)
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    deleteDisabled(row) {
      if (this.categoryKey == 'lowcode' || row.categoryKey == 'lowcode') {
        return true
      } else if (row.maintainer) {
        const { userId } = this.$store.state.user
        return (row.maintainer || '').split(',').indexOf(userId) !== -1 && row.createdBy !== userId
      } else {
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.title{
  color: #131414;
  line-height: 24px;
  margin-bottom: 4px;
}
.classifyContent{
  padding: 12px 12px 0 12px;
  border: 1px solid #DCDFE6;
  max-height: 400px;
  overflow-y: auto;
}
.radio{
  display: block;
  margin-bottom: 16px;
}
::v-deep.dialog-wrap .el-dialog .el-dialog__body{
 padding-top: 4px;
}
</style>
